package com.shelpe.services.sinbad.entity.jpa;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.AttributeConverter;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;

import com.shelpe.services.sinbad.controller.dto.vo.KeywordRanking;
import com.shelpe.services.sinbad.entity.jpa.WantRank.WantRankPK;
import com.shelpe.services.sinbad.service.utils.EntityUtils;

import lombok.Data;

@Entity(name = "want_rank")
@IdClass(WantRankPK.class)
@Data
public class WantRank {
	@Id
	@Column(name="tactics_id")
	private long tacticsID;
	@Id
	@Column(name="keyword_id")
	private long keywordID;
	private int wantRank;
	@Convert(converter=DoingConverter.class)
	private Doing doing;
	private int originalValue;
	@Column(name="msg")
	private String message;
	@Column(name="update_time_keyword")
	@Convert(converter=EntityUtils.Day2IntConverter.class)
	private Date updatedTime;
	
	public void from(KeywordRanking ranking){
		this.setKeywordID(ranking.getKeywordID());
		this.setWantRank(ranking.getRank());
		this.setOriginalValue(ranking.getPrice());
		this.setUpdatedTime(new Date());
		this.setDoing(Doing.executable);
	}
	
	
	public static enum Doing{
		executable(0), locked(1), negative(2), overflowed(3);
		private int value;

		private Doing(int v) {
			this.value = v;
		}

		public int getValue() {
			return this.value;
		}
	}
	
	public static class DoingConverter implements AttributeConverter<Doing, Integer> {

		@Override
		public Integer convertToDatabaseColumn(Doing attribute) {
			return attribute != null ? attribute.getValue() : Doing.executable.getValue();
		}

		@Override
		public Doing convertToEntityAttribute(Integer dbData) {
			Doing status = Doing.executable;
			for (Doing s : Doing.values()) {
				if (s.getValue() == dbData) {
					status = s;
					break;
				}
			}
			return status;
		}
	}
	
	@Data
	public static class WantRankPK implements Serializable{
		private static final long serialVersionUID = 1L;
		@Column(name="tactics_id")
		private long tacticsID;
		@Column(name="keyword_id")
		private long keywordID;
		
		public WantRankPK(){}
		public WantRankPK(long tID, long kID){
			this.tacticsID = tID;
			this.keywordID = kID;
		}
	}
}
